package com.lahuan.export_import;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;


@ActiveProfiles("hikari")
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ExportMysqlData.class)
@SpringBootApplication(scanBasePackages = "com.lahuan")
public class ExportMysqlData {

    @Autowired
    JdbcTemplate jdbcTemplate;
    // 文件名
    private String filePath="E:\\test\\javaExport.csv";
    private BufferedWriter out = null;
    private void init() throws Exception {
        Path path = Paths.get(filePath);
        if(!Files.exists(path)){
            Files.createFile(path);
        }
        out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(new File(filePath), true)));
    }
    public  void append( String content) throws IOException {
         out.write(content+"\r\n");
         out.flush();
    }

    private void close() throws IOException {
        out.close();
    }
    @Test
    public void test() throws Exception {
        int max = 10_000_000;
        int pageSize = 10000;
        int page =  max /pageSize;
        long insertStart = System.currentTimeMillis();
        init();
        int count=0;
        for (int i = 0; i <= page; i++) {
            int limit = i*pageSize;
            List<String> lists = jdbcTemplate.query("select * from t_order limit "+limit+","+pageSize, (resultSet, i1) -> {
                String sn = resultSet.getString("order_sn");
                long id = resultSet.getLong("id");
                return id + "," + sn+"\r\n";
            });
            if(lists.size()==0){
                break;
            }
            count+=lists.size();
            String ctx = lists.stream().reduce((a, b) -> a + b).get();
            append(ctx);
            log.info("当前大小:{}",count);
        }
        close();
        long insertEnd = System.currentTimeMillis();
        long insertCost= insertEnd - insertStart;
        System.out.println("mysql cost:"+insertCost);
    }
}
